from flask import request, jsonify
from app.api import api_bp
from app.models import Report, Project, TestResult

@api_bp.route('/reports', methods=['GET'])
def get_reports():
    """获取所有报告"""
    project_id = request.args.get('project_id')
    
    if project_id:
        reports = Report.query.filter_by(project_id=project_id).all()
    else:
        reports = Report.query.all()
    
    return jsonify([report.to_dict() for report in reports])

@api_bp.route('/reports', methods=['POST'])
def create_report():
    """创建新报告"""
    data = request.get_json()
    
    if not data or not data.get('name') or not data.get('project_id'):
        return jsonify({'error': '报告名称和项目ID不能为空'}), 400
    
    # 验证项目是否存在
    project = Project.query.get(data['project_id'])
    if not project:
        return jsonify({'error': '项目不存在'}), 404
    
    report = Report(
        name=data['name'],
        project_id=data['project_id'],
        total_cases=data.get('total_cases', 0),
        passed_cases=data.get('passed_cases', 0),
        failed_cases=data.get('failed_cases', 0),
        pass_rate=data.get('pass_rate', 0),
        duration=data.get('duration', '')
    )
    
    try:
        report.save()
        return jsonify(report.to_dict()), 201
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@api_bp.route('/reports/<int:report_id>', methods=['GET'])
def get_report(report_id):
    """获取单个报告"""
    report = Report.query.get_or_404(report_id)
    
    # 获取报告的测试结果
    test_results = TestResult.query.filter_by(report_id=report_id).all()
    
    report_data = report.to_dict()
    report_data['test_results'] = [result.to_dict() for result in test_results]
    
    return jsonify(report_data)

@api_bp.route('/reports/<int:report_id>', methods=['DELETE'])
def delete_report(report_id):
    """删除报告"""
    report = Report.query.get_or_404(report_id)
    
    try:
        report.delete()
        return jsonify({'message': '报告删除成功'})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@api_bp.route('/reports/<int:report_id>/download', methods=['GET'])
def download_report(report_id):
    """下载报告"""
    report = Report.query.get_or_404(report_id)
    
    try:
        # 这里应该实现报告生成和下载逻辑
        # 暂时返回模拟数据
        return jsonify({
            'message': '报告下载链接生成成功',
            'download_url': f'/api/reports/{report_id}/download/file'
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@api_bp.route('/projects/<int:project_id>/run-tests', methods=['POST'])
def run_project_tests(project_id):
    """执行项目的所有测试用例"""
    # 验证项目是否存在
    project = Project.query.get_or_404(project_id)
    
    try:
        # 这里应该实现批量测试执行逻辑
        # 暂时返回模拟数据
        return jsonify({
            'message': '项目测试执行成功',
            'report_id': 1,  # 模拟生成的报告ID
            'result': {
                'total_cases': 10,
                'passed_cases': 8,
                'failed_cases': 2,
                'pass_rate': '80%',
                'duration': '2分30秒'
            }
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500